#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 17:02
import time
from typing import List

from domain.report.common.period_enum import PeriodEnum
from infrastructure.common.threadingPool import ThreadPool
from domain.report.dto.profit_dto import ProfitDTO, ProfitSchema
from infrastructure.util.selenium_spider import RequestMethodEnum, SeleniumSpider2JsonConfiguration, spider2json


"""
https://xueqiu.com/snowman/S/SH600050/detail#/XJLLB
财务报表接口：https://stock.xueqiu.com/v5/stock/finance/cn/cash_flow.json?symbol=SH600050&type=Q4&is_detail=true&count=5&timestamp=
"""



@ThreadPool(thread_name_prefix="xueqiu_")
def _balance_sheet_spider(stock_code:str, period:PeriodEnum=None, count:int=5):
    arr = stock_code.split(".")
    stock_code = f"{arr[1]}{arr[0]}"
    url = f"""
        https://stock.xueqiu.com/v5/stock/finance/cn/cash_flow.json?symbol={stock_code}
        &type={"all" if period is None else f"Q{period.value}"}
        &is_detail=true&count={count}&timestamp={time.time()}
    """
    configuration = SeleniumSpider2JsonConfiguration()
    configuration.add_prepose_url(f"https://xueqiu.com/snowman/S/{stock_code}/detail#/XJLLB", method=RequestMethodEnum.get)
    configuration.set_data_url(url)
    result = spider2json(configuration)
    return result


_xueqiuPeriod2_localPeriod = {
    "一季报": PeriodEnum.first_quarter,
    "中报": PeriodEnum.half_year,
    "三季报": PeriodEnum.three_quarter,
    "年报": PeriodEnum.year
}


def _spider_assembler(data:dict, stock_code, period: PeriodEnum) -> List[ProfitDTO]:
    """
    未定位元素：cash_received_from_bond_issue
    """
    dto_list = list()
    if data and len(data) > 0 and data.get("data", None) and data["data"].get("list", None):
        data_list = data["data"]["list"]
        for item in data_list:
            dto = ProfitDTO()
            dto.stock_code = stock_code
            dto.stock_id = stock_code.split(".")[0]
            dto.year = int(item["report_name"][:3])
            dto.period = _xueqiuPeriod2_localPeriod[item["report_name"][4:]]
            ProfitSchema.set(dto, "branch_paid_to_minority_holder", item["branch_paid_to_minority_holder"])
            ProfitSchema.set(dto, "c_pay_acq_const_fiolta", item["cash_paid_for_assets"])
            ProfitSchema.set(dto, "c_pay_dist_dpcp_int_exp", item["cash_paid_of_distribution"])
            ProfitSchema.set(dto, "c_paid_to_for_empl", item["cash_paid_to_employee_etc"])
            ProfitSchema.set(dto, "cash_pay_for_debt", item["cash_pay_for_debt"])
            ProfitSchema.set(dto, "cash_received_from_investor", item["cash_received_from_investor"])
            ProfitSchema.set(dto, "cash_received_of_absorb_invest", item["cash_received_of_absorb_invest"])
            ProfitSchema.set(dto, "cash_received_of_borrowing", item["cash_received_of_borrowing"])
            ProfitSchema.set(dto, "cash_received_of_resume_invest", item["cash_received_of_dspsl_invest"])
            ProfitSchema.set(dto, "cash_received_of_other_financing", item["cash_received_of_othr_fa"])
            ProfitSchema.set(dto, "cash_received_of_other_invest", item["cash_received_of_othr_ia"])
            ProfitSchema.set(dto, "cash_received_of_other_operate", item["cash_received_of_othr_oa"])
            ProfitSchema.set(dto, "cash_received_of_sales_service", item["cash_received_of_sales_service"])
            ProfitSchema.set(dto, "effect_of_exchange_change", item["effect_of_exchange_chg_on_cce"])
            ProfitSchema.set(dto, "c_cash_equ_end_period", item["final_balance_of_cce"])
            ProfitSchema.set(dto, "c_paid_goods_s", item["goods_buy_and_service_cash_pay"])
            ProfitSchema.set(dto, "c_cash_equ_start_period", item["initial_balance_of_cce"])
            ProfitSchema.set(dto, "invest_income_cash_received", item["invest_income_cash_received"])
            ProfitSchema.set(dto, "invest_paid_cash", item["invest_paid_cash"])
            ProfitSchema.set(dto, "n_cash_flows_fnc_act", item["ncf_from_fa"])
            ProfitSchema.set(dto, "n_cashflow_invest_act", item["ncf_from_ia"])
            ProfitSchema.set(dto, "n_cashflow_act", item["ncf_from_oa"])
            ProfitSchema.set(dto, "net_cash_of_disposal_assets", item["net_cash_of_disposal_assets"])
            ProfitSchema.set(dto, "net_cash_of_disposal_branch", item["net_cash_of_disposal_branch"])
            ProfitSchema.set(dto, "cash_equ_increase", item["net_increase_in_cce"])
            ProfitSchema.set(dto, "other_cash_paid_to_financing", item["othrcash_paid_relating_to_fa"])
            ProfitSchema.set(dto, "other_cash_paid_to_invest", item["othrcash_paid_relating_to_ia"])
            ProfitSchema.set(dto, "other_cash_paid_to_operate", item["othrcash_paid_relating_to_oa"])
            ProfitSchema.set(dto, "payments_of_all_taxes", item["payments_of_all_taxes"])
            ProfitSchema.set(dto, "refund_of_tax_and_levies", item["refund_of_tax_and_levies"])
            ProfitSchema.set(dto, "sub_total_cash_in_financing", item["sub_total_of_ci_from_fa"])
            ProfitSchema.set(dto, "sub_total_cash_in_invest", item["sub_total_of_ci_from_ia"])
            ProfitSchema.set(dto, "sub_total_cash_in_operate", item["sub_total_of_ci_from_ia"])
            ProfitSchema.set(dto, "sub_total_cash_out_financing", item["sub_total_of_cos_from_fa"])
            ProfitSchema.set(dto, "sub_total_cash_out_invest", item["sub_total_of_cos_from_ia"])
            ProfitSchema.set(dto, "sub_total_cash_out_operate", item["sub_total_of_cos_from_oa"])
            ProfitSchema.set(dto, "net_cash_remain_from_branch", item["net_cash_amt_from_branch"])
    return dto_list

def spider(stock_code:str, period:PeriodEnum=None, count:int=5) -> List[ProfitDTO]:
    result = _balance_sheet_spider(stock_code, period, count)
    dtos = None
    if result and len(result) > 0:
        dtos = _spider_assembler(result, stock_code, period)
    return dtos